<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
    <title>Document</title>
    <style>
        #box{
            width:100px;
            height:100px;
            background-color: lightcoral;
            position: absolute;
            left:0;
            top:0;
        }
    </style>
</head>
<body>
    <div id="box"></div>
    <script>
        let box = document.querySelector('#box');
        //定义每次按键的步长，默认是10px
        let step = 10;
        //获取该元素距离页面顶部的距离
        let offsetTop = box.offsetTop;//0
         //获取该元素距离页面左侧的距离
        let offsetLeft = box.offsetLeft;//0
        function moveBox(event){//event.target
            console.log(event);
            switch(event.key){
                case 'ArrowUp':
                    offsetTop-=step;//向上移动
                    break;
                case 'ArrowDown':
                    offsetTop+=step;//向下移动
                    break;
                case 'ArrowLeft':
                    offsetLeft-=step;//向左移动
                    break;
                case 'ArrowRight':
                    offsetLeft+=step;//向右移动
                    break;
            }
            //更新box的样式，移动到指定的位置 
            box.style.left = offsetLeft+'px';
            box.style.top = offsetTop+'px';
        }
        //给box添加按钮按下的事件,当键盘上有键按下的时候，执行moveBox方法
        document.addEventListener('keydown',moveBox);
    </script>
</body>
</html>